<template>
  <div>
    <el-dialog
      :title="titlecom"
      :visible.sync="dialogFormVisible"
      width="1300px"
    >
      <!-- :rules="rules" -->
      <el-form :model="form" label-width="100px" class="demo-ruleForm">
        <el-form-item
          label="分类"
          :label-width="formLabelWidth"
          prop="consumablestypeid"
        >
          <el-select
            v-model="form.consumablestypeid"
            placeholder="分类"
            class="specificationInput"
            filterable
          >
            <el-option
              v-for="a in reqCategory1"
              :key="a.id"
              :label="a.name"
              :value="a.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="展示图"
          :label-width="formLabelWidth"
          prop="image"
        >
          <el-upload
            action=""
            :http-request="uploadFile"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            multiple
            :file-list="imgList"
            :limit="10"
            class="avatar-uploader"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible1" :modal="false">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
          <draggable v-model="imgList" :options="{ handle: '.handle' }">
            <div
              v-for="(file, index) in imgList"
              :key="index"
              class="sortable-item"
            >
              <i class="el-icon-menu handle"></i>
              <el-dialog :visible.sync="dialogVisible1" :modal="false">
                <img
                  width="100%"
                  :src="dialogImageUrl"
                  alt=""
                  class="sortable-img"
                />
              </el-dialog>
            </div>
          </draggable>

          <div class="lunboTag">
            建议尺寸：300*300，上传一张就可以
          </div>
        </el-form-item>
        <el-form-item label="标题" prop="content" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :rows="4"
            style="width: 547px"
            placeholder="请输入内容"
            v-model="form.title"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model="form.price" class="specificationInput"></el-input>
        </el-form-item>
        <el-form-item label="来源" :label-width="formLabelWidth" prop="laiyuan">
          <el-input v-model="form.laiyuan" class="specificationInput"></el-input>
        </el-form-item>
        <el-form-item label="链接地址" :label-width="formLabelWidth" prop="url">
          <el-input v-model="form.url" class="specificationInput"></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="beizhu">
          <el-input v-model="form.beizhu" class="specificationInput"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="quedingtianjia()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addconsumablesadd,
  updateconsumablesupdate,
  getcopywritingtypes,
} from "@/api/consumables";
import { upload } from "@/api/editor.js";
import EditorBar from "@/components/Editor";
import draggable from "vuedraggable";
export default {
  components: {
    EditorBar,
    draggable,
  },
  data() {
    return {
      reqCategory1: [],
      isClear: false,
      dialogVisible: false,
      dialogFormVisible: false,
      formLabelWidth: "180px",
      form: {
        consumablestypeid: "",
        title: "",
        image: "",
        price: "",
        laiyuan: "",
        url: "",
        beizhu: "",
      },
      imgList: [],
      dialogImageUrl: "",
      dialogVisible1: false,
      rules: {
        consumablestypeid: [
          { required: true, message: "请选择分类", trigger: "blur" },
        ],
        image: [
          {
            required: true,
            message: "请上传图片",
            trigger: "blur",
          },
        ],
      },
      qubie: 0,
    };
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible1 = true;
      console.log(file);
    },
    //轮播图移除图片
    handleRemove(file, fileList) {
      // fileList是剩下的照片
      this.imgList = fileList;
    },
    //轮播图上传
    uploadFile(param) {
      var file = param.file;
      const formData = new FormData();
      formData.append("file", file);
      upload(formData, param).then((res) => {
        if (res.code == 0) {
          // ---------------------------这是商品轮播图 最后要通过 图片逗号拼接
          this.imgList.push({ url: res.data });
        }
      });
      console.log(this.imgList);
    },
    changeselect(val) {
      // console.log(val);
      this.form.servetypeid = val.id;
      this.form.servetype = val.name;
    },
    change() {},
    async getcopywritingtypes() {
      let result = await getcopywritingtypes();
      console.log(result);
      if (result.code == 0) {
        this.reqCategory1 = result.data;
      }
    },
    // 将富文本获取回来数据上剔除掉html标签
    getSimpleText(html) {
      var re1 = new RegExp("<.+?>", "g"); //匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
      var msg = html.replace(re1, ""); //执行替换成空字符
      return msg;
    },
    add() {
      this.form = {
        consumablestypeid: "",
        title: "",
        image: "",
        price: "",
        laiyuan: "",
        url: "",
        beizhu: "",
      };
      this.qubie = 0;
      this.getcopywritingtypes();
      this.dialogFormVisible = true;
      this.imgList = [];
    },
    edit(val) {
      this.form = {
        consumablestypeid: "",
        title: "",
        image: "",
        price: "",
        laiyuan: "",
        url: "",
        beizhu: "",
      };
      this.qubie = 1;
			 this.imgList = [];
			 console.log("图片",val.image);
      this.getcopywritingtypes();
      this.form = Object.assign(this.form, val);
      this.dialogFormVisible = true;
      this.imgList = [];
		  val.image.forEach((item) => {
          this.imgList.push({ url: item });
        });
    },
    // 关闭
    handleClose() {
      this.dialogFormVisible = false;
      this.$emit("refresh");
    },

    async quedingtianjia() {
      if (this.qubie == 0) {
        // console.log(this.form.endtime);
        // var originalDate = new Date(this.form.endtime);
        // var year = originalDate.getFullYear();
        // var month = (originalDate.getMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，需要加1，然后确保两位数
        // var day = originalDate.getDate().toString().padStart(2, "0"); // 确保两位数
        // var formattedDateString = `${year}-${month}-${day}`;
        // console.log(formattedDateString);

        let param = {
          consumablestypeid: this.form.consumablestypeid,
          title: this.getSimpleText(this.form.title),
          image: this.form.image,
          price: parseFloat(this.form.price),
          laiyuan: this.form.laiyuan,
          url: this.form.url,
          beizhu: this.form.beizhu,

        };
        let result = await addconsumablesadd(param);
        if (result.code == 0) {
          this.$message({
            message: `添加成功`,
            type: "success",
          });
          this.handleClose();
        }
      } else if (this.qubie == 1) {
        let param = {
          id: parseInt(this.form.id),
          consumablestypeid: this.form.consumablestypeid,
          title: this.getSimpleText(this.form.title),
          image: this.form.image,
          price: parseFloat(this.form.price),
          laiyuan: this.form.laiyuan,
          url: this.form.url,
          beizhu: this.form.beizhu,
        };
        let result = await updateconsumablesupdate(param);
        if (result.code == 0) {
          this.$message({
            message: `修改文案成功`,
            type: "success",
          });
          this.handleClose();
        }
      }
    },
  },
  watch: {
    imgList: {
      handler(newVal) {
        // console.log("监听", newVal);
        // 这里创建新的数组 用逗号进行隔开 主要是接口要求
        let imagearr = [];
        const result = newVal.map((item) => `${item.url}`).join(",");
        this.form.image = result;
        console.log("猪嗨", this.form.image);
      },
      deep: true,
    },
  },
  computed: {
    titlecom() {
      if (this.qubie == 0) {
        return "添加";
      } else {
        return "修改";
      }
    },
  },
};
</script>

<style scoped lang="scss">
.specificationInput {
  width: 250px;
}
.avatar-uploader-icon[data-v-22a48a68] {
  border: 1px dashed #d9d9d9;
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: center;
  flex-direction: column;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
  height: 300px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.addguigeBtn {
  margin-left: 100px;
  margin-bottom: 22px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 180px;
  height: 180px;
  line-height: 180px;
  text-align: center;
}

.avatar {
  width: 180px;
  height: 180px;
  display: block;
}
v-deep .el-upload--picture-card {
  width: 300px !important;
  height: 300px !important;
}
.specificationInput1 {
  width: 150px;
}
</style>
